package eerbaar.shared.internal.message;

import java.util.ArrayList;
import java.util.List;

import eerbaar.shared.message.IMessageReader;
import eerbaar.shared.message.IMessageReaderList;
import eerbaar.shared.message.Message;

public class DefaultList implements IMessageReaderList {

    private final IMessageReaderList allList;
    private final List<IMessageReader> handlers = new ArrayList<IMessageReader>();
    private boolean debug;

    public DefaultList(IMessageReaderList allList) {

        this.allList = allList;
    }

    @Override
    public <H extends IMessageReader> void addReader(H handler) {

        this.handlers.add(handler);
        if (this.debug) {
            System.out.println("IMessageReaderList.addReader(" + handler + ") "
                    + this.handlers.size());
        }
    }

    @Override
    public <H extends IMessageReader> void removeReader(H handler) {

        this.handlers.remove(handler);
        if (this.debug) {
            System.out.println("IMessageReaderList.removeReader(" + handler
                    + ") " + this.handlers.size());
        }
    }

    @Override
    public <E extends Message> void sendMessage(E request) {

        IMessageReader[] array = this.handlers.toArray(new IMessageReader[] {});
        for (IMessageReader h : array) {
            h.read(request);
        }

        if (this.allList != null) {
            this.allList.sendMessage(request);
        }
    }

    @Override
    public void setDebug(boolean debug) {
        this.debug = debug;
    }

}
